package com.sky.service.common.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.common.DishFlavorMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Author:JinFeng
 * @Date: 2025/09/24 17:07
 * @Description:
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return Result.success(pageResult);

    }


    @Override
    public Result<String> addWithFlavors(DishDTO dishDTO) {
        // 一.校验参数
        if(Objects.isNull(dishDTO)
                || Objects.isNull(dishDTO.getCategoryId())
                || StringUtils.isBlank(dishDTO.getName())
                || Objects.isNull(dishDTO.getPrice())
                || StringUtils.isBlank(dishDTO.getImage())){
            throw new BaseException("参数异常，请检查！！");
        }
        // 二.处理业务
        //0.菜品名称去重校验
        Long count = dishMapper.countByName(dishDTO.getName());
        if(count > 0) {
            throw new BaseException("菜品名称已存在，请更换！！");
        }
        //1.保存菜品数据到菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        // 2.保存菜品与口味数据到菜品口味表
        // 为每个口味都设置菜品ID
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        dishFlavorMapper.insertBatch(flavors);
        // 三.封装数据
        return Result.success();
    }
}
